package com.jucai.pppeiyouclient;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.content.FileProvider;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.bumptech.glide.signature.StringSignature;
import com.fm.openinstall.OpenInstall;
import com.fm.openinstall.listener.AppWakeUpListener;
import com.fm.openinstall.model.AppData;
import com.fm.openinstall.model.Error;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jucai.pppeiyouclient.base.BaseActivity;
import com.jucai.pppeiyouclient.base.BaseApplication;
import com.jucai.pppeiyouclient.base.BaseParam;
import com.jucai.pppeiyouclient.base.PermissionListener;
import com.jucai.pppeiyouclient.base.TokenParam;
import com.jucai.pppeiyouclient.bean.AccompanyBean;
import com.jucai.pppeiyouclient.bean.AdBean;
import com.jucai.pppeiyouclient.bean.CityBean;
import com.jucai.pppeiyouclient.bean.IndexRedBean;
import com.jucai.pppeiyouclient.bean.RedInfoBean;
import com.jucai.pppeiyouclient.bean.RewardBean;
import com.jucai.pppeiyouclient.comm.CommonMethod;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.AnimUtil;
import com.jucai.pppeiyouclient.utils.AppUtil;
import com.jucai.pppeiyouclient.utils.FileUtils;
import com.jucai.pppeiyouclient.utils.LocationHelper;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.SharedPreferencesUtil;
import com.jucai.pppeiyouclient.utils.TextCheckUtils;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.view.activity.ActivitiesInitiateActivity;
import com.jucai.pppeiyouclient.view.activity.BrowserActivity;
import com.jucai.pppeiyouclient.view.activity.CitySelectActivity;
import com.jucai.pppeiyouclient.view.activity.CommonH5Activity;
import com.jucai.pppeiyouclient.view.activity.GetOrderListActivity;
import com.jucai.pppeiyouclient.view.activity.FriendListActivity;
import com.jucai.pppeiyouclient.view.activity.LoginActivity;
import com.jucai.pppeiyouclient.view.activity.MessageActivity;
import com.jucai.pppeiyouclient.view.activity.MyActivitiesActivity;
import com.jucai.pppeiyouclient.view.activity.MyOrdersActivity;
import com.jucai.pppeiyouclient.view.activity.OrderSettingActivity;
import com.jucai.pppeiyouclient.view.activity.PersonalSettingsActivity;
import com.jucai.pppeiyouclient.view.activity.RegisterSecondStepActivity;
import com.jucai.pppeiyouclient.view.activity.RewardListActivity;
import com.jucai.pppeiyouclient.view.activity.SettingActivity;
import com.jucai.pppeiyouclient.view.activity.TransactionRecordActivity;
import com.jucai.pppeiyouclient.view.activity.WalletDetailActivity;
import com.jucai.pppeiyouclient.view.dialog.MessageShowDialog;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.HttpHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.sharesdk.onekeyshare.OnekeyShare;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.jucai.pppeiyouclient.R.id.common_back;
import static com.jucai.pppeiyouclient.R.id.main_drawer;
import static com.jucai.pppeiyouclient.R.id.me_activity;
import static com.jucai.pppeiyouclient.R.id.me_friends;
import static com.jucai.pppeiyouclient.R.id.me_image;
import static com.jucai.pppeiyouclient.R.id.me_settings;
import static com.jucai.pppeiyouclient.R.id.me_wallet;
import static com.jucai.pppeiyouclient.utils.ImageHandleUtils.FILE_PROVIDER;

public class MainActivity extends BaseActivity implements AppWakeUpListener {

    private static final String TAG = "MainActivity : ";
    private static final int SDK_PAY_FLAG = 1001;
    private boolean isExit = false;
    private TextView titleMe, titleText, titleFind;

    private DrawerLayout mainDrawer;
    private ActionBarDrawerToggle drawerToggle;
    private ImageView mainImage, backImageView;
    private TextView mainNick, mainOnline, mainOrderCount, mainMonthRunning, mainClassroom, mainReward,
            mainSystemNews, mainResponseNews, mainFriendNews, mainSetting, mainGetOrder,
            mainPublish, mainOrderState;
    private ViewFlipper mainAdFlipper;

    private CircleImageView meImage;
    private TextView meNick, meOrderState, meServiceScore, meDealRate, meOrder,
            meActivity, meWallet, meNewsCount, meFriends, meSettings, meBeTraveller, meFriendsRecommend;
    private RelativeLayout meNewsCenter, mainTopRelativeLayout, meMainTopRelativeLayout;
    private LinearLayout llOrderCount, llMonthRunning;

    private ContentLoadingProgressBar loadProgressBar;

//    private WebView findWeb;

    private AccompanyBean accompany;

    private String price, serviceCity, startTime, endTime, carPrice;

    private List<AdBean> adList = new ArrayList<>();

    private int priceType, isOpen, withCar, withCamera, cityId;

    private long startTimeStamp, endTimeStamp;

    private String phoneIMEI;

    private Handler mHandler = new Handler();

    private FrameLayout fltRed;
    private RelativeLayout rltRed;
    private ImageView ivRed;
    private TextView tv_red_subhead;
    private String apkDownloadLink;
    private boolean isLocationGranted;
    private ImageView ivTopDot;
    private ImageView ivMenuDot;
    private boolean type = true;
    private Timer mTimer;

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(LoginUtils.getToken(this)) && !TextUtils.isEmpty(LoginUtils.getMember_id(this))) {
            checkRed();
            getMessageTpye();

            loadCityInfo();

            if (ProjectGlobalVar.isSendLocation){
                ProjectGlobalVar.isSendLocation = false;
                type = false;
                sendLocaton();
            }
        }
    }


    /**
     * 启动5分钟上传一次坐标
     */
    private void sendLocaton() {
        try {
            mTimer = new Timer();
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    LocationHelper.getInstance().setBaiDuLocationCallBack(new LocationHelper.BaiDuLocationCallBack() {
                        @Override
                        public void onSuccess(BDLocation bdLocation) {
                            if (TextUtils.isEmpty(LoginUtils.getToken(MainActivity.this)) || TextUtils.isEmpty(LoginUtils.getMember_id(MainActivity.this))) {
                                stopTimer();
                                type = true;
                                return;
                            }
                            BaseApplication.getBaseApplication().mLatitude = bdLocation.getLatitude();
                            BaseApplication.getBaseApplication().mLongitude = bdLocation.getLongitude();
                            BaseApplication.getBaseApplication().mCity = bdLocation.getCity();
                            uploadLocaton();
                        }

                        @Override
                        public void onError(BDLocation bdLocation) {
                        }
                    });
                    LocationHelper.getInstance().start();
                }
            }, 1000, 5 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer.purge();
            mTimer = null;
        }
    }

    /**
     * 5分钟上传一次坐标到后台
     */
    private void uploadLocaton() {
        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Accompany_Mail.getMailUnRead");
        param.put("member_id", LoginUtils.getMember_id(this));
        param.put("token", LoginUtils.getToken(this));
        param.put("lontitue", BaseApplication.getBaseApplication().mLatitude + "");
        param.put("latitue", BaseApplication.getBaseApplication().mLongitude + "");
        CommonRequestNetData.getJsonStringDataByEncrpt(MainActivity.this, param, new CommonRequestNetData.ResultCallBack() {
            @Override
            public void parseJsonString(String str) {
            }

            @Override
            public void onError(String str) {
            }
        });


    }

    protected void loadCityInfo() {
        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Public_City.getlist");
        CommonRequestNetData.getJsonArrayData(MainActivity.this, param, true, new CommonRequestNetData.JsonArrayCallBack() {
            @Override
            public void parseJsonArray(JSONArray jsonArray) {
                LogUtils.e(TAG + "jsArr = " + jsonArray);
                List<CityBean> cityList = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<CityBean>>() {
                }.getType());
                Collections.sort(cityList);
                BaseApplication.cityList = cityList;
            }
        });
    }

    private void getMessageTpye() {
        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Accompany_Mail.getMailUnRead");
        param.put("member_id", LoginUtils.getMember_id(this));
        param.put("token", LoginUtils.getToken(this));
        CommonRequestNetData.getJsonObjectData(MainActivity.this, false, param, new CommonRequestNetData.JsonObjectCallBack() {
            @Override
            public void parseJsonObject(JSONObject jsonObject) {
                try {
                    String count = jsonObject.getString("count");
                    LogUtils.e("MainActivity MessageType json = " + jsonObject.toString());
                    int intCount = Integer.parseInt(count);
                    if (intCount > 0) {
                        ivMenuDot.setVisibility(View.VISIBLE);
                        ivTopDot.setVisibility(View.VISIBLE);
                    } else {
                        ivMenuDot.setVisibility(View.GONE);
                        ivTopDot.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    ivMenuDot.setVisibility(View.GONE);
                    ivTopDot.setVisibility(View.GONE);
                    e.printStackTrace();
                }
            }
        });
    }

    private void setMessageTpye() {
        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Accompany_Mail.readAllMail");
        param.put("member_id", LoginUtils.getMember_id(this));
        param.put("token", LoginUtils.getToken(this));
        CommonRequestNetData.getJsonObjectData(MainActivity.this, false, param, new CommonRequestNetData.JsonObjectCallBack() {
            @Override
            public void parseJsonObject(JSONObject jsonObject) {
                try {
                    ivMenuDot.setVisibility(View.GONE);
                    ivTopDot.setVisibility(View.GONE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= 23) {
            BaseActivity.onRuntimePermissionRequest(new String[]{Manifest.permission.READ_PHONE_STATE,Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, new PermissionListener() {
                @Override
                public void onGranted() {
                    TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
                    phoneIMEI = TelephonyMgr.getDeviceId();
                    LocationHelper.getInstance().setBaiDuLocationCallBack(new LocationHelper.BaiDuLocationCallBack() {
                        @Override
                        public void onSuccess(BDLocation bdLocation) {
                            BaseApplication.getBaseApplication().mLatitude = bdLocation.getLatitude();
                            BaseApplication.getBaseApplication().mLongitude = bdLocation.getLongitude();
                            BaseApplication.getBaseApplication().mCity = bdLocation.getCity();

                        }

                        @Override
                        public void onError(BDLocation bdLocation) {

                        }
                    });
                    LocationHelper.getInstance().start();

                    if (!TextUtils.isEmpty(LoginUtils.getToken(MainActivity.this)) && !TextUtils.isEmpty(LoginUtils.getMember_id(MainActivity.this))) {
                        if (type) {
                            type = false;
                            sendLocaton();
                        }
                    }
                }

                @Override
                public void onDenied(List<String> deniedPermissions) {
                    ToastUtils.showToast("不同意该权限将导致本软件无法使用，请到权限管理打开该权限！");
                }
            });
        } else {
            LocationHelper.getInstance().setBaiDuLocationCallBack(new LocationHelper.BaiDuLocationCallBack() {
                @Override
                public void onSuccess(BDLocation bdLocation) {
                    BaseApplication.getBaseApplication().mLatitude = bdLocation.getLatitude();
                    BaseApplication.getBaseApplication().mLongitude = bdLocation.getLongitude();
                    BaseApplication.getBaseApplication().mCity = bdLocation.getCity();

                }

                @Override
                public void onError(BDLocation bdLocation) {

                }
            });
            LocationHelper.getInstance().start();

            if (!TextUtils.isEmpty(LoginUtils.getToken(MainActivity.this)) && !TextUtils.isEmpty(LoginUtils.getMember_id(MainActivity.this))) {
                if (type) {
                    type = false;
                    sendLocaton();
                }
            }
        }
        initTitle();
        initMain();
        initLeftDrawer();
//        initRightDrawer();
//        renzDialog = new AlertDialog.Builder(MainActivity.this)
//                .setMessage("未实名认证不可进行订单操作，是否进行实名认证？")
//                .setPositiveButton("去认证!", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        startActivity(new Intent(MainActivity.this, RegisterThirdStepActivity.class));
//                    }
//                }).setNegativeButton("不，谢谢", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        dialogInterface.dismiss();
//                    }
//                });

    }

    private void initTitle() {

        titleMe = (TextView) findViewById(R.id.common_title_me);
        titleText = (TextView) findViewById(R.id.common_title_text_main);
        titleFind = (TextView) findViewById(R.id.common_title_find);
        backImageView = (ImageView) findViewById(common_back);

        fltRed = (FrameLayout) findViewById(R.id.flt_red);
        fltRed.setVisibility(View.GONE);
        rltRed = (RelativeLayout) findViewById(R.id.rlt_red);
        tv_red_subhead = (TextView) findViewById(R.id.tv_red_subhead);

        ivRed = (ImageView) findViewById(R.id.iv_red);

        titleMe.setTextColor(Color.parseColor("#ffffff"));
        titleText.setTextColor(Color.parseColor("#efb336"));
        titleFind.setTextColor(Color.parseColor("#ffffff"));

    }

    private void initMain() {

        ivTopDot = (ImageView) findViewById(R.id.iv_top_dot);
        ivMenuDot = (ImageView) findViewById(R.id.iv_menu_dot);
        mainDrawer = (DrawerLayout) findViewById(main_drawer);
        mainImage = (ImageView) findViewById(R.id.main_image);
        mainOrderState = (TextView) findViewById(R.id.main_order_state);
        mainNick = (TextView) findViewById(R.id.main_nick);
        mainOnline = (TextView) findViewById(R.id.main_online);
        mainOrderCount = (TextView) findViewById(R.id.main_order_count);
        mainMonthRunning = (TextView) findViewById(R.id.main_month_running);
        mainClassroom = (TextView) findViewById(R.id.main_classroom);
        mainReward = (TextView) findViewById(R.id.main_reward);
        mainSystemNews = (TextView) findViewById(R.id.main_system_news);
        mainResponseNews = (TextView) findViewById(R.id.main_response_news);
        mainFriendNews = (TextView) findViewById(R.id.main_friend_news);
        mainSetting = (TextView) findViewById(R.id.main_settings);
        mainGetOrder = (TextView) findViewById(R.id.main_get_order);
        mainPublish = (TextView) findViewById(R.id.main_publish);
        mainAdFlipper = (ViewFlipper) findViewById(R.id.main_ad_flipper);
        loadProgressBar = (ContentLoadingProgressBar) findViewById(R.id.load_progressB_bar);
        mainTopRelativeLayout = (RelativeLayout) findViewById(R.id.main_top);
        meMainTopRelativeLayout = (RelativeLayout) findViewById(R.id.me_main_top);
        llOrderCount = (LinearLayout) findViewById(R.id.ll_order_count);
        llMonthRunning = (LinearLayout) findViewById(R.id.ll_month_running);

        drawerToggle = new ActionBarDrawerToggle(MainActivity.this, mainDrawer, R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (TextUtils.isEmpty(LoginUtils.getMember_id(MainActivity.this)) || TextUtils.isEmpty(LoginUtils.getToken(MainActivity.this))) {
                    ToastUtils.showToast("请先登录");
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));
                            ActivityCollector.removeActivity(MainActivity.this);
                        }
                    }, 500);
                } else {
                    if (mainDrawer.isDrawerOpen(GravityCompat.START)) {
                        titleMe.setVisibility(View.VISIBLE);
                        titleFind.setVisibility(View.VISIBLE);
                        backImageView.setVisibility(View.INVISIBLE);
                        titleMe.setTextColor(Color.parseColor("#efb336"));
                        titleText.setTextColor(Color.parseColor("#ffffff"));
                        titleFind.setTextColor(Color.parseColor("#ffffff"));
                    } else if (mainDrawer.isDrawerOpen(GravityCompat.END)) {
                        titleText.setText("发现");
                        titleMe.setVisibility(View.VISIBLE);
                        titleFind.setVisibility(View.VISIBLE);
                        backImageView.setVisibility(View.INVISIBLE);
                        titleMe.setTextColor(Color.parseColor("#ffffff"));
                        titleText.setTextColor(Color.parseColor("#ffffff"));
                        titleFind.setTextColor(Color.parseColor("#efb336"));
                    }
                }
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (TextUtils.isEmpty(LoginUtils.getMember_id(MainActivity.this)) || TextUtils.isEmpty(LoginUtils.getToken(MainActivity.this))) {
                    ToastUtils.showToast("请先登录");
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));
                            ActivityCollector.removeActivity(MainActivity.this);
                        }
                    }, 500);
                } else {
                    titleText.setText("PP优质陪游");
                    titleMe.setVisibility(View.VISIBLE);
                    titleFind.setVisibility(View.VISIBLE);
                    backImageView.setVisibility(View.GONE);
                    titleMe.setTextColor(Color.parseColor("#ffffff"));
                    titleText.setTextColor(Color.parseColor("#efb336"));
                    titleFind.setTextColor(Color.parseColor("#ffffff"));
                }
            }
        };

    }

    private void initLeftDrawer() {

        meImage = (CircleImageView) findViewById(me_image);
        meNick = (TextView) findViewById(R.id.me_nick);
        meOrderState = (TextView) findViewById(R.id.me_order_state);
        meServiceScore = (TextView) findViewById(R.id.me_service_score);
        meDealRate = (TextView) findViewById(R.id.me_deal_rate);
        meOrder = (TextView) findViewById(R.id.me_order);
        meActivity = (TextView) findViewById(me_activity);
        meWallet = (TextView) findViewById(me_wallet);
        meNewsCount = (TextView) findViewById(R.id.me_news_count);
        meFriends = (TextView) findViewById(me_friends);
        meSettings = (TextView) findViewById(me_settings);
        meBeTraveller = (TextView) findViewById(R.id.me_be_traveller);
        meFriendsRecommend = (TextView) findViewById(R.id.me_friends_recommend);
        meNewsCenter = (RelativeLayout) findViewById(R.id.me_news_center);

        apkDownloadLink = "";

    }

    private void initRightDrawer() {

        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Find_Find.getFindIndexURL");

        CommonRequestNetData.getJsonObjectData(MainActivity.this, false, param, new CommonRequestNetData.JsonObjectCallBack() {
            @Override
            public void parseJsonObject(JSONObject jsonObject) {
                try {
                    LogUtils.e(TAG + "find jsObj = " + jsonObject.toString());
                    String url = jsonObject.getString("accompany_find");
                    String strUrl = url;
                    if (!TextUtils.isEmpty(url) && !url.substring(url.length()-1).equals("&")){
                        strUrl += "&";
                    }

                    strUrl += "app_type=accompany" + "&lng=" + BaseApplication.getBaseApplication().mLongitude + "&lat=" + BaseApplication.getBaseApplication().mLatitude+ "&member_id=" + LoginUtils.getMember_id(MainActivity.this) + "&token=" + LoginUtils.getToken(MainActivity.this) ;
                    CommonH5Activity.startCommH5(MainActivity.this, 5, strUrl, null, null, null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    protected void initData() {
        try {
            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
            ProjectGlobalVar.version = info.versionName;
            ProjectGlobalVar.versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        checkUpdate();

    }

    @Override
    protected void loadNetData() {

        getInfo();

    }

    @Override
    protected void setListener() {

        titleMe.setOnClickListener(this);
        titleText.setOnClickListener(this);
        titleFind.setOnClickListener(this);
        mainImage.setOnClickListener(this);
        mainClassroom.setOnClickListener(this);
        mainReward.setOnClickListener(this);
        mainSystemNews.setOnClickListener(this);
        mainResponseNews.setOnClickListener(this);
        mainFriendNews.setOnClickListener(this);
        mainSetting.setOnClickListener(this);
        mainGetOrder.setOnClickListener(this);
        mainPublish.setOnClickListener(this);
        backImageView.setOnClickListener(this);
        mainDrawer.setDrawerListener(drawerToggle);
        mainTopRelativeLayout.setOnClickListener(this);
        meMainTopRelativeLayout.setOnClickListener(this);
        llOrderCount.setOnClickListener(this);
        llMonthRunning.setOnClickListener(this);

        meImage.setOnClickListener(this);
        meOrder.setOnClickListener(this);
        meActivity.setOnClickListener(this);
        meWallet.setOnClickListener(this);
        meNewsCenter.setOnClickListener(this);
        meFriends.setOnClickListener(this);
        meSettings.setOnClickListener(this);
        meBeTraveller.setOnClickListener(this);
        meFriendsRecommend.setOnClickListener(this);
        meOrderState.setOnClickListener(this);

        mainOrderState.setOnClickListener(this);

        fltRed.setOnClickListener(this);
        rltRed.setOnClickListener(this);
    }

    private void getAds() {
        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Public_UserIndex.accompanyIndex");

        double mLatitude = BaseApplication.getBaseApplication().mLatitude;
        double mLongitude = BaseApplication.getBaseApplication().mLongitude;
        if (mLatitude == 0.0) {
            mLatitude = 22.799344;
        }
        if (mLongitude == 0.0) {
            mLongitude = 108.360942;
        }
        param.put("point", mLatitude + "," + mLongitude);
        LogUtils.e(TAG + "  param = " + param.toString());
        CommonRequestNetData.getJsonArrayData(MainActivity.this, param, false, new CommonRequestNetData.JsonArrayCallBack() {
            @Override
            public void parseJsonArray(JSONArray jsonArray) {
                try {
                    LogUtils.e(TAG + "ads ic_back_forward jsArr = " + jsonArray.toString());
                    adList = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<AdBean>>() {
                    }.getType());
                    LogUtils.e(TAG + "adList = " + adList);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 0; i < adList.size(); i++) {

                                AdBean ad = adList.get(i);
                                View v = View.inflate(MainActivity.this, R.layout.view_flipper_ad_layout, null);
                                TextView adTitle = (TextView) v.findViewById(R.id.flipper_content);
                                adTitle.setText(ad.getAdv_title());
                                final String url = ad.getAdv_url();
                                final String title = ad.getAdv_title();
                                mainAdFlipper.addView(v);

                                v.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        LogUtils.e(TAG + "adUrl = " + url + ",adTitle = " + title);
//                                    CommonH5Activity.startCommH5(MainActivity.this, 5, url, null, null, null);
                                        Intent intent = new Intent(MainActivity.this, CommonH5Activity.class);
                                        intent.putExtra("type", 5);
                                        intent.putExtra("url", url);

                                        startActivity(intent);
                                    }
                                });
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void getInfo() {
        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Accompany_Info.getAccompanyInfo");
        param.put("token", LoginUtils.getToken(this));
        param.put("member_id", LoginUtils.getMember_id(this));
        CommonRequestNetData.getJsonStringDataByEncrpt(MainActivity.this, param, new CommonRequestNetData.ResultCallBack() {
            @Override
            public void parseJsonString(String str) {
                try {

                    LogUtils.e(TAG + "AccompanyInfo = " + str);
                    loadProgressBar.setVisibility(View.GONE);
                    AnimUtil.goneAlpha(loadProgressBar, 1000);
                    accompany = new Gson().fromJson(str, AccompanyBean.class);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LoginUtils.saveMember_avatar(MainActivity.this, accompany.getMember_avatar());
                            Glide.with(MainActivity.this).load(accompany.getMember_avatar()).signature(new StringSignature("01")).into(mainImage);

                            if (accompany.getAccompany_accept_state() == 1) {
                                long nowTime = (new Date().getTime() / 1000);
                                long endTime = accompany.getAccompany_accept_end_time_timestamp();
                                long startTime = accompany.getAccompany_accept_start_time_timestamp();
                                LogUtils.d(nowTime + "|" + startTime + "|" + endTime);
//                            if (startTime < (nowTime + 60) && nowTime < endTime) {//接口已设置状态
                                mainOrderState.setTextColor(Color.parseColor("#EFB336"));
                                mainOrderState.setText("接单中");
                                meOrderState.setTextColor(Color.parseColor("#EFB336"));
                                meOrderState.setText("接单中");
//                            } else {//接口已设置
//                                closeAcceptState();
//                            }
                            } else {
                                closeAcceptState();
                            }


                            SharedPreferencesUtil.saveStringPreference(MainActivity.this, "rongyun", "rongyun_isfocus", "0");

                            mainNick.setText(accompany.getMember_realname());
                            mainOnline.setText(accompany.getAccompany_online_time());
                            mainOrderCount.setText(accompany.getAccompany_deal_num());
                            mainMonthRunning.setText(accompany.getAccompany_cash_flow());
                            Glide.with(MainActivity.this)
                                    .load(accompany.getMember_avatar())
                                    .into(meImage);

                            meNick.setText(accompany.getMember_realname());
                            meServiceScore.setText(accompany.getAccompany_score() + "");
                            meDealRate.setText(accompany.getAccompany_deal_rate());


                            LogUtils.d("Accompany:" + accompany.toString());

                            price = accompany.getAccompany_price();
//                        overflowPrice = accompany.getAccompany_overflow_price();
                            serviceCity = accompany.getAccompany_server_city();
                            startTime = accompany.getAccompany_accept_start_time();
                            endTime = accompany.getAccompany_accept_end_time();
                            carPrice = accompany.getAccompany_car_price();
                            priceType = accompany.getAccompany_price_type();
                            isOpen = accompany.getAccompany_accept_state();
                            withCar = accompany.getAccompany_car_state();
                            withCamera = accompany.getAccompany_photograph_state();
                            startTimeStamp = accompany.getAccompany_accept_start_time_timestamp();
                            endTimeStamp = accompany.getAccompany_accept_end_time_timestamp();
                            cityId = accompany.getAccompany_server_city_id();

                            SharedPreferencesUtil.saveStringPreference(MainActivity.this, "PREFERENCE", "avatar", accompany.getMember_avatar());
                            SharedPreferencesUtil.saveStringPreference(MainActivity.this, "PREFERENCE", "name", accompany.getMember_realname());

                            SharedPreferencesUtil.saveStringPreference(MainActivity.this, "PREFERENCE", "accompany_id", accompany.getAccompany_id());
                            SharedPreferencesUtil.saveStringPreference(MainActivity.this, "PREFERENCE", "service_city", accompany.getAccompany_server_city());
                            SharedPreferencesUtil.saveStringPreference(MainActivity.this, "PREFERENCE", "service_city_id", accompany.getAccompany_server_city_id() + "");
                            SharedPreferencesUtil.saveStringPreference(MainActivity.this, "PREFERENCE", "phone_number", accompany.getMember_phone());
                            SharedPreferencesUtil.saveIntPreference(MainActivity.this, "PREFERENCE", "member_status", accompany.getMember_status());

                            if (TextUtils.isEmpty(accompany.getMember_realname())) {
                                SharedPreferencesUtil.saveStringPreference(MainActivity.this, "PREFERENCE", "phone", accompany.getMember_phone());
                                SharedPreferencesUtil.saveStringPreference(MainActivity.this, "PREFERENCE", "password", "for_main_not_pass");

                                Intent i = new Intent(MainActivity.this, RegisterSecondStepActivity.class);
                                i.putExtra("extra_member_avatar", accompany.getMember_avatar());
                                i.putExtra("extra_member_sexual", accompany.getMember_sexual());
                                i.putExtra("extra_member_age", accompany.getMember_age());
                                i.putExtra("extra_member_education", accompany.getMember_education());
                                i.putExtra("extra_member_occupation", accompany.getMember_occupation());
                                i.putExtra("extra_accompany_server_city", accompany.getMember_city());
                                i.putExtra("extra_member_desc", accompany.getMember_desc());
                                startActivity(i);
                            } else {
                                getAds();
                            }

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String str) {
                if (TextUtils.equals(str, "未找到登录信息,请重新登录")) {
                    LoginUtils.saveToken(MainActivity.this, "");
                    LoginUtils.saveMember_id(MainActivity.this, "");
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    ActivityCollector.removeActivity(MainActivity.this);
                }
            }
        });
    }

    private void closeAcceptState() {

        mainOrderState.setTextColor(Color.parseColor("#FF0000"));
        mainOrderState.setText("暂停接单");
        meOrderState.setTextColor(Color.parseColor("#FF0000"));
        meOrderState.setText("暂停接单");

        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Accompany_Info.updateAccompanyInfo");
        param.put("accompany_accept_state", "0");

        CommonRequestNetData.getJsonStringData(this, param, false, new CommonRequestNetData.JsonStringCallBack() {
            @Override
            public void parseJsonString(String str) {
                LogUtils.e(TAG + "str = " + str);
            }
        });

    }

    @Override
    public void onClick(View view) {
        if (TextUtils.isEmpty(LoginUtils.getMember_id(MainActivity.this)) || TextUtils.isEmpty(LoginUtils.getToken(MainActivity.this))) {
            ToastUtils.showToast("请先登录");
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    ActivityCollector.removeActivity(MainActivity.this);
                }
            }, 500);
        } else {

            switch (view.getId()) {
                case common_back:
                    mainDrawer.closeDrawers();
                    break;
                case R.id.common_title_text_main:
                    if (mainDrawer.isDrawerOpen(GravityCompat.START) ||
                            mainDrawer.isDrawerOpen(GravityCompat.END)) {
                        mainDrawer.closeDrawers();

                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                titleMe.setTextColor(Color.parseColor("#ffffff"));
                                titleText.setTextColor(Color.parseColor("#efb336"));
                                titleFind.setTextColor(Color.parseColor("#ffffff"));
                            }
                        }, 300);
                    }
                    break;
                case R.id.main_top:
                    startActivity(new Intent(this, PersonalSettingsActivity.class));
                    break;
                case R.id.me_main_top:
                    startActivity(new Intent(this, PersonalSettingsActivity.class));
                    break;
                case R.id.common_title_me:
                    if (mainDrawer.isDrawerOpen(GravityCompat.START)) {
                        mainDrawer.closeDrawer(GravityCompat.START);

                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                titleMe.setTextColor(Color.parseColor("#ffffff"));
                                titleText.setTextColor(Color.parseColor("#efb336"));
                                titleFind.setTextColor(Color.parseColor("#ffffff"));
                            }
                        }, 300);
                    } else {

                        if (mainDrawer.isDrawerOpen(GravityCompat.END)) {
                            mainDrawer.closeDrawer(GravityCompat.END);
                        }
                        mainDrawer.openDrawer(GravityCompat.START);

                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                titleMe.setTextColor(Color.parseColor("#efb336"));
                                titleText.setTextColor(Color.parseColor("#ffffff"));
                                titleFind.setTextColor(Color.parseColor("#ffffff"));
                            }
                        }, 300);
                    }
                    break;

                case R.id.common_title_find: //发现
                    initRightDrawer();
//                    if (mainDrawer.isDrawerOpen(GravityCompat.END)) {
//                        mainDrawer.closeDrawer(GravityCompat.END);
//
//                        mHandler.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                titleMe.setTextColor(Color.parseColor("#ffffff"));
//                                titleText.setTextColor(Color.parseColor("#efb336"));
//                                titleFind.setTextColor(Color.parseColor("#ffffff"));
//                            }
//                        }, 300);
//                    } else {
//
//                        if (mainDrawer.isDrawerOpen(GravityCompat.START)) {
//                            mainDrawer.closeDrawer(GravityCompat.START);
//                        }
//                        mainDrawer.openDrawer(GravityCompat.END);
//                        mHandler.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                titleMe.setTextColor(Color.parseColor("#ffffff"));
//                                titleText.setTextColor(Color.parseColor("#ffffff"));
//                                titleFind.setTextColor(Color.parseColor("#efb336"));
//                            }
//                        }, 300);
//                    }
                    break;

                case R.id.main_classroom:


                    BaseParam baseParam = new BaseParam("Classroom_Classroom.Classroom");

                    CommonRequestNetData.getJsonObjectData(MainActivity.this, baseParam.getParam(), false, new CommonRequestNetData.JsonObjectCallBack() {
                        @Override
                        public void parseJsonObject(JSONObject jsonObject) {
                            try {
                                String url = jsonObject.getString("url");
                                Intent intent = new Intent(MainActivity.this, BrowserActivity.class);
                                intent.putExtra("url", url);
                                startActivity(intent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });

                    break;
                case R.id.me_image:
                    startActivity(new Intent(this, PersonalSettingsActivity.class));
                    break;
                case R.id.main_image:
                    // 2017-5-14 11:25:06 点击头像调转
                    startActivity(new Intent(this, PersonalSettingsActivity.class));
                    break;
                case R.id.main_reward:
                    Intent intent = new Intent(MainActivity.this, RewardListActivity.class);
                    startActivity(intent);

                   /* TokenParam tokenParam = new TokenParam(this, "Accompany_Info.getRewardList");

                    CommonRequestNetData.getJsonArrayData(this, tokenParam.getParam(), true, new CommonRequestNetData.JsonArrayCallBack() {
                        @Override
                        public void parseJsonArray(JSONArray jsonArray) {
                            try {
                                String temp = "";
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    temp += (i + 1) + ":" + jsonArray.getJSONObject(i).getString("reward_content") + "\n";
                                }
                                if (TextCheckUtils.isEmpty(temp)) {
                                    temp = "暂无奖励!";
                                }
                                MessageShowDialog messageShowDialog = new MessageShowDialog(MainActivity.this);
                                TextView messageShowTitle = (TextView) messageShowDialog.findViewById(R.id.message_dialog_title);
                                TextView messageShowContent = (TextView) messageShowDialog.findViewById(R.id.message_dialog_content);
                                messageShowTitle.setText("奖励");
                                messageShowContent.setText(temp);
                                messageShowDialog.show();
                                messageShowDialog.setOnclickListener(MainActivity.this);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });*/

                    break;

                case R.id.main_system_news:
                    startActivity(new Intent(MainActivity.this, MessageActivity.class));
                    break;

                case R.id.main_response_news:
                    MyOrdersActivity.startMyOrders(MainActivity.this, 0);
                    break;

                case R.id.main_friend_news:
                    MyActivitiesActivity.startActivities(MainActivity.this, 0);
                    break;

                case R.id.main_settings:
                    startOrderActivity();
                    break;

                case R.id.main_get_order:
                    if (Build.VERSION.SDK_INT >= 23) {
                        BaseActivity.onRuntimePermissionRequest(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new PermissionListener() {
                            @Override
                            public void onGranted() {
                                isLocationGranted = true;
                            }

                            @Override
                            public void onDenied(List<String> deniedPermissions) {
                                isLocationGranted = false;
                                ToastUtils.showToast("获取定位权限失败！请在设置中开启！");
                            }
                        });
                    } else
                        isLocationGranted = true;
                    if (isLocationGranted) {
                        startActivity(new Intent(MainActivity.this, GetOrderListActivity.class));
                    }
                    //                if (!TextUtils.isEmpty(accompany.getAccompany_id())) {
//                } else {
//                    renzDialog.show();
//                }
                    break;

                case R.id.main_publish:

                    //                if (!TextUtils.isEmpty(accompany.getAccompany_id())) {
                    startActivity(new Intent(MainActivity.this, ActivitiesInitiateActivity.class));
//                } else {
//                    renzDialog.show();
//                }
                    break;

                case R.id.me_order_state:
                    startOrderActivity();
                    break;

                case R.id.me_order:
                    MyOrdersActivity.startMyOrders(MainActivity.this, 0);
                    break;

                case R.id.me_activity:
                    MyActivitiesActivity.startActivities(MainActivity.this, 0);
                    break;

                case R.id.me_wallet:

                    startActivity(new Intent(MainActivity.this, WalletDetailActivity.class));
                    break;

                case R.id.me_news_center:
                    setMessageTpye();
                    startActivity(new Intent(MainActivity.this, MessageActivity.class));
                    break;

                case R.id.me_friends:

                    //                    if (RongIM.getInstance() != null)
//                        RongIM.getInstance().startConversationList(this);
                    startActivity(new Intent(MainActivity.this, FriendListActivity.class));
                    break;

                case R.id.me_settings:

                    startActivity(new Intent(MainActivity.this, SettingActivity.class));
                    break;

                case R.id.me_be_traveller:
                    /**
                     * 启动陪游端
                     */
                    if (!CommonMethod.toStartOtherApplication(MainActivity.this, "com.ppuser.client"))

                    {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("提示");
                        builder.setMessage("您还没有下载PP优约");
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.setPositiveButton("去下载", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent();

                                intent.setAction("android.intent.action.VIEW");

                                intent.addCategory("android.intent.category.DEFAULT");

                                intent.setData(Uri.parse("http://openinstall.io/c/gbh4yz/NN000001"));

                                startActivity(intent);
                            }
                        });
                        builder.create().show();
                    }

                    break;

                case R.id.me_friends_recommend:
                    stawebTj();
//                    HashMap<String, String> param = new HashMap<>();
//                    param.put("service", "Extension_Qrcode.getQrCode");
//                    param.put("member_id", LoginUtils.getMember_id(MainActivity.this));
//                    param.put("token", LoginUtils.getToken(MainActivity.this));
//
//
//                    CommonRequestNetData.getJsonObjectData(MainActivity.this, param, false, new CommonRequestNetData.JsonObjectCallBack() {
//
//                        @Override
//                        public void parseJsonObject(JSONObject jsonObject) {
//                            try {
//                                LogUtils.e(TAG + "shareData = " + jsonObject.toString());
//                                String url = jsonObject.getString("url");
//                                showShare("title", url, url);
//                            } catch (Exception e) {
//                            }
//                        }
//                    });

                    break;

                case R.id.main_order_state:
                    startOrderActivity();
                    break;
                case R.id.flt_red://红包
                    fltRed.setVisibility(View.GONE);
                    break;
                case R.id.rlt_red:
                    if (isGetRed)
                        fltRed.setVisibility(View.GONE);
                    else
                        getIndexRed();
                    break;

                case R.id.ll_order_count:
                    startActivity(new Intent(MainActivity.this, MyOrdersActivity.class));
                    break;
                case R.id.ll_month_running:
                    startActivity(new Intent(MainActivity.this, TransactionRecordActivity.class));
                    break;
                default:
                    break;
            }
        }
    }

    private void stawebTj() {
        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Public_Share.getRecommentUrl");
        param.put("member_id", LoginUtils.getMember_id(this));
        param.put("token", LoginUtils.getToken(this));
        CommonRequestNetData.getJsonObjectData(MainActivity.this, false, param, new CommonRequestNetData.JsonObjectCallBack() {
            @Override
            public void parseJsonObject(JSONObject jsonObject) {
                //LogUtils.e(TAG + "find jsObj = " + jsonObject.toString());
                //Log.i("webcviwewUrl",jsonObject.toString());
                try {
                    String url = jsonObject.getString("URL");
                    //  String url = jsonObject.getString("accompany_find")+"app_type=accompany";
                    //Log.i("webcviwewUrl",url);
                    CommonH5Activity.startCommH5(MainActivity.this, 5, url + "&state=1", null, null, null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 领红包
     */
    public void getIndexRed() {
        Map<String, String> mapRegister = new HashMap<>();
        mapRegister.put("service", "GoldCoin_GoldCoin.receive");
        mapRegister.put("member_id", LoginUtils.getMember_id(this));
        mapRegister.put("token", LoginUtils.getToken(this));
        mapRegister.put("user_name", LoginUtils.getMember_nickname(this));
        mapRegister.put("user_name", LoginUtils.getMember_nickname(this));
        CommonRequestNetData.getJsonStringDataByEncrpt(this, mapRegister, new CommonRequestNetData.ResultCallBack() {
            @Override
            public void parseJsonString(String str) {
                isLoading = false;
                RedInfoBean redInfoBean = new Gson().fromJson(str, RedInfoBean.class);
                ivRed.setImageResource(R.mipmap.rebbaged);
                tv_red_subhead.setText("恭喜您，获得" + redInfoBean.receive_money + "个金币");
                isGetRed = true;
            }

            @Override
            public void onError(String str) {
                ToastUtils.showToast("领取失败!");
                fltRed.setVisibility(View.GONE);
            }
        });
    }

    private boolean isGetRed;
    private boolean isLoading;

    /**
     * \判断是否可以领红包
     */
    private void checkRed() {
        Map<String, String> mapRegister = new HashMap<>();
        mapRegister.put("service", "GoldCoin_GoldCoin.isreceive");
        mapRegister.put("member_id", LoginUtils.getMember_id(this));
        mapRegister.put("token", LoginUtils.getToken(this));
        CommonRequestNetData.getJsonStringDataByEncrpt(this, mapRegister, new CommonRequestNetData.ResultCallBack() {
            @Override
            public void parseJsonString(String str) {
                isLoading = false;
                IndexRedBean indexRedBean = new Gson().fromJson(str, IndexRedBean.class);
                if (indexRedBean.getRed() == 1) {
                    isGetRed = false;
                    fltRed.setVisibility(View.VISIBLE);
                    fltRed.findFocus();
                    fltRed.requestFocus();
                } else {
                    fltRed.setVisibility(View.GONE);
                    fltRed.clearFocus();
                }
            }

            @Override
            public void onError(String str) {

            }
        });
    }

    OnekeyShare oks;

    /**
     * demo临时存放 需要封装
     */
    private void showShare(String text, String url, String imgUrl) {
        if (oks == null)
            oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网、QQ和QQ空间使用
        oks.setTitle("PP优约");
        // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(text);
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl(imgUrl);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("PP优约");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(url);

        // 启动分享GUI
        oks.show(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mainDrawer.isDrawerOpen(GravityCompat.START) || mainDrawer.isDrawerOpen(GravityCompat.END)) {
                LogUtils.e("close drawers");
                mainDrawer.closeDrawers();
                titleMe.setTextColor(Color.parseColor("#ffffff"));
                titleText.setTextColor(Color.parseColor("#efb336"));
                titleFind.setTextColor(Color.parseColor("#ffffff"));
            } else {
                LogUtils.e("do ic_back_forward");
                exitBy2Click();
            }
        }
        return false;
    }

    private void exitBy2Click() {
        Timer tExit;
        if (isExit == false) {
            isExit = true;
            ToastUtils.showToast("再按一次退出程序");
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    @Override
    public void onWakeUpFinish(AppData appData, Error error) {
        if (error == null) {
            //获取渠道数据
//            ToastUtils.showToast("获取渠道数据:" + appData.getChannel());
            //获取个性化安装数据
            BaseApplication.member_extension_id = appData.getChannel();
        } else {

        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        //此处要调用，否则App在后台运行时，会无法截获
        OpenInstall.getWakeUp(intent, this);
    }

    class JavaScriptInterface {

        @JavascriptInterface
        public void showToast(String webMessage) {
            LogUtils.e(TAG + "onJsConfirm -->" + webMessage);
            String[] info = webMessage.split("&");
            for (int i = 0; i < info.length; i++) {
                String temp = info[i];
                String[] temp2 = temp.split("=");

            }
        }
    }

    private void startOrderActivity() {


        LogUtils.d(price + "|" + carPrice + "|" + isOpen + "|" + withCar + "|" + priceType + "|" + withCamera + "|" + endTime + "|" + startTime + "|" + endTimeStamp + "|" + startTimeStamp);

        Intent setIntent = new Intent(MainActivity.this, OrderSettingActivity.class);

        setIntent.putExtra("price", price);
        setIntent.putExtra("car_price", carPrice);

        setIntent.putExtra("is_open", isOpen);
        setIntent.putExtra("with_car", withCar);
        setIntent.putExtra("price_type", priceType);
        setIntent.putExtra("with_camera", withCamera);

        setIntent.putExtra("end_time", endTime);
        setIntent.putExtra("start_time", startTime);
        setIntent.putExtra("end_time_stamp", endTimeStamp);
        setIntent.putExtra("start_time_stamp", startTimeStamp);

        if (TextUtils.equals(serviceCity, "北京")) {
            cityId = 36;
        }

        setIntent.putExtra("service_city_id", cityId);
        setIntent.putExtra("service_city", serviceCity);

        startActivity(setIntent);

    }

    //自定义方法

    private void checkUpdate() {

        BaseParam baseParam = new BaseParam("Public_UpdateFunction.accompany_update");
        baseParam.put("version_sn", AppUtil.getVersion(this));

        CommonRequestNetData.getJsonObjectData(this, baseParam.getParam(), false, new CommonRequestNetData.JsonObjectCallBack() {
            @Override
            public void parseJsonObject(JSONObject jsonObject) {
                try {
                    getLocation();

                    boolean state = jsonObject.getBoolean("update_status");
                    final int update_type = jsonObject.getInt("update_type");//默认 service 下载 1 跳浏览器下载
                    if (state) {
                        apkDownloadLink = jsonObject.getString("update_url");
                        tipsUpdate(jsonObject.getString("update_content"),update_type);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void downloadApk() {

        FinalHttp finalHttp = new FinalHttp();
        finalHttp.configTimeout(5000);
        finalHttp.configCharset("UTF-8");

        final Dialog dialog = new AlertDialog.Builder(this).create();
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_query);
        final TextView titleTextView = (TextView) window.findViewById(R.id.titleTextView);
        final TextView contentTextView = (TextView) window.findViewById(R.id.contentTextView);
        final TextView confirmTextView = (TextView) window.findViewById(R.id.confirmTextView);
        final TextView cancelTextView = (TextView) window.findViewById(R.id.cancelTextView);
        cancelTextView.setVisibility(View.GONE);
        confirmTextView.setText("取消");

        titleTextView.setText("正在下载");
        contentTextView.setText("已下载");
        contentTextView.append(": 0 %");

        final String filePath = FileUtils.getDownPath() + "/ppclient.apk";

        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }

        final HttpHandler httpHandler;

        httpHandler = finalHttp.download(apkDownloadLink, filePath, new AjaxCallBack<File>() {
            @Override
            public void onStart() {
                super.onStart();
                contentTextView.setText("已下载");
                contentTextView.append(": 0 %");
            }

            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
                int progress;
                if (current != count && current != 0) {
                    progress = (int) (current / (float) count * 100);
                } else {
                    progress = 100;
                }
                String progressString = "已下载：" + progress + " %";
                contentTextView.setText(progressString);
            }

            @Override
            public void onSuccess(File t) {
                super.onSuccess(t);
                startInstallApk(new File(filePath));
                dialog.cancel();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                ToastUtils.showToast("下载更新包失败");
            }
        });

        confirmTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                httpHandler.stop();
                dialog.cancel();
            }
        });

    }

    private void tipsUpdate(String content, final int type) {

        new AlertDialog.Builder(this)
                .setTitle("检测到新版本，是否更新？")
                .setMessage(content)
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (type == 1){
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            intent.addCategory("android.intent.category.DEFAULT");
                            intent.setData(Uri.parse(apkDownloadLink));
                            startActivity(intent);
                            return;
                        }

                        if (Build.VERSION.SDK_INT >= 23) {
                            BaseActivity.onRuntimePermissionRequest(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, new PermissionListener() {
                                @Override
                                public void onGranted() {
                                    downloadApk();
                                }

                                @Override
                                public void onDenied(List<String> deniedPermissions) {
                                    ToastUtils.showToast("获取文件存储权限失败！请在设置中开启！");
                                }
                            });
                        } else {
                            downloadApk();
                        }
                    }
                })
                .show();

    }

    private void startInstallApk(File file) {

        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri uri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(this, FILE_PROVIDER, file);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }else {
                uri = Uri.fromFile(file);
            }

            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            startActivity(intent);
        } catch (Exception e) {
            ToastUtils.showToast("打开文件失败，请前往应用商店更新。");
            e.printStackTrace();
        }

    }

    private void getLocation() {

        LocationClient locationClient = new LocationClient(getApplicationContext());
        LocationClientOption locationClientOption = new LocationClientOption();
        locationClientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        locationClientOption.setCoorType("bd09ll");
        locationClientOption.setIsNeedAddress(true);
        locationClientOption.setOpenGps(true);
        locationClientOption.setLocationNotify(true);
        locationClientOption.setIsNeedLocationDescribe(true);
        locationClientOption.setIsNeedLocationPoiList(true);
        locationClientOption.setIgnoreKillProcess(false);
        locationClientOption.SetIgnoreCacheException(false);
        locationClientOption.setEnableSimulateGps(false);
        locationClient.setLocOption(locationClientOption);

        BDLocationListener bdLocationListener = new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {

                TokenParam tokenParam = new TokenParam(MainActivity.this, "Accompany_Location.putLocation");
                tokenParam.put("lontitue", bdLocation.getLongitude() + "");
                tokenParam.put("latitue", bdLocation.getLatitude() + "");

                CommonRequestNetData.getJsonStringDataByEncrpt(MainActivity.this, tokenParam.getParam(), new CommonRequestNetData.ResultCallBack() {
                    @Override
                    public void parseJsonString(String str) throws Exception {
                        new CountDownTimer(300000, 1000) {
                            @Override
                            public void onTick(long millisUntilFinished) {

                            }

                            @Override
                            public void onFinish() {
                                getLocation();
                            }
                        }.start();
                    }

                    @Override
                    public void onError(String str) throws Exception {

                    }
                    /* @Override
                    public void parseJsonString(String str) {
                        try {
                            new CountDownTimer(300000, 1000) {
                                @Override
                                public void onTick(long millisUntilFinished) {

                                }

                                @Override
                                public void onFinish() {
                                    getLocation();
                                }
                            }.start();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }*/
                });

            }

            @Override
            public void onConnectHotSpotMessage(String s, int i) {
                LogUtils.d(s);
            }
        };

        locationClient.registerLocationListener(bdLocationListener);
        locationClient.start();

    }

}
